<template>
 <div class="params">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- <Breadcrumb /> -->

    <el-card>
        <el-alert show-icon :closable="false"
          title="注意，只允许为第三级分类设置相关参数"
          type="warning">
        </el-alert>

        <el-row>
          <el-col>
            <span>选择商品分类：</span>
              <el-cascader
                v-model="selectKeys"
                :options="cateList"
                expandTrigger="hover"
                :props="cateProps"
                @change="handleChange"></el-cascader>
          </el-col>
        </el-row>


        <el-tabs v-model="activeName" @tab-click="changeTab">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnClick" @click="addTk = true">添加参数</el-button>
            <el-table :data="manyData" border stripe>
              <el-table-column  type="expand">
                <template slot-scope="scope">
                    <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="deleteTag(scope.row, i)">{{item}} </el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>  
              </el-table-column>              
              <el-table-column label="#" type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditTk(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteAttrs(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBtnClick" @click="addTk = true">添加属性</el-button>
            <el-table :data="onlyData" border stripe>
              <el-table-column  type="expand">
                <template slot-scope="scope">
                    <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="deleteTag(scope.row, i)">{{item}} </el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>  
              </el-table-column>     
              <el-table-column label="#" type="index"></el-table-column>
              <el-table-column label="属性名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditTk(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteAttrs(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
    </el-card>


    <!-- 添加参数 -->
    <el-dialog
      :title=" '添加' + titleText"
      :visible.sync="addTk"
      width="50%"
      @close="resetAddTk"
      >
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addTk = false">取 消</el-button>
        <el-button type="primary" @click="addAttrs">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 编辑参数 -->
    <el-dialog
      :title=" '编辑' + titleText"
      :visible.sync="editTk"
      width="50%"
      @close="resetEditTk"
      >
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editTk = false">取 消</el-button>
        <el-button type="primary" @click="editAttrs">确 定</el-button>
      </span>
    </el-dialog>



 </div>
</template>

<script>
import Breadcrumb from "../breadcrumb.vue";
 export default {
   created(){
     this.getCateList()
   },
  components:{
    Breadcrumb
  },
   data(){
     return {
       queryInfo:{

       },
       cateList:[],
      cateProps:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
      },
        selectKeys:[],
        activeName:'many',
      manyData:[],
      onlyData:[],
      addTk:false,
      addForm:{attr_name:''},
      addFormRules:{
        attr_name:[{required: true, message: "请输入参数名称", trigger: "blur"}] 
      },
      editTk:false,
      editForm:{},
      editFormRules:{
        attr_name:[{required: true, message: "请输入参数名称", trigger: "blur"}] 
      },

     }
   },
   methods:{
     async getCateList(){
        const { data: res } = await this.$http.get("categories");
        if (res.meta.status !== 200) return this.$message.error("获取商品分类失败!");
        this.cateList = res.data
        // console.log(res);
     },
     // 级联选择框选中项发生变化 
    handleChange(){

      if(this.selectKeys.length !== 3){
        this.selectKeys = []
        this.manyData = []
        this.onlyData = []
        return
      }

      this.getParamsData()
     },
     changeTab(){
      this.getParamsData()
     },
     // 获取参数的列表数据
     async getParamsData(){
       if(this.selectKeys.length !== 3){
         this.selectKeys = []
         return 
       }
       // 选中的是三级分类
      // 根据所选分类的id 和当前所处的面板，获取对应的参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params:{sel:this.activeName}
        });                                                                                                                                                                      
        if (res.meta.status !== 200) return this.$message.error("更新商品参数失败!");
              // console.log(res);
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 控制文本框的显示与隐藏
          item.inputVisible = false
          item.inputValue = ''
        })
        if(this.activeName === 'many'){
          this.manyData = res.data
        }else{
          this.onlyData = res.data
        }
     },
     resetAddTk(){
       this.$refs.addFormRef.resetFields()
     },
     resetEditTk(){
       this.$refs.editFormRef.resetFields()
     },
      addAttrs(){
        this.$refs.addFormRef.validate(async valid => {
          if(!valid) return 
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,{
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          });
          if (res.meta.status !== 201) return this.$message.error("添加属性参数失败!");          
          this.$message.success("添加属性参数成功!");  
          this.addTk = false
          this.getCateList()
        })
      },
      async showEditTk(id){
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
          params:{attr_sel: this.activeName}
        });
        if (res.meta.status !== 200) return this.$message.error("获取属性失败!");
        this.editForm = res.data
        this.editTk = true
      },
      editAttrs(){
        this.$refs.editFormRef.validate(async valid => {
          if(!valid) return 
          const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          });
          if (res.meta.status !== 200) return this.$message.error("编辑属性参数失败!");          
          this.$message.success("编辑属性参数成功!");  
          this.editTk = false
          this.getParamsData()
        })
      },
      async deleteAttrs(id){
        const confirms = await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((err) => err);
         
         if(confirms !== 'confirm'){
             return this.$message.info('已取消删除');  
         }
         const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error("删除属性失败");
        console.log(res);
        this.$message.success('删除成功！')
        this.getParamsData()
      },
      showInput(that) {
        that.inputVisible = true;
        // $nextTick 当页面上的元素被重新渲染后，才会指定回调函数中的代码
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      async handleInputConfirm(that){
        if (that.inputValue.trim().length === 0) {
          that.inputValue = '';
          that.inputVisible = false;
          return
        }
        that.attr_vals.push(that.inputValue.trim())
        that.inputVisible = false;
        that.inputValue = '';

        this.saveAttrs(that)
      },
      async deleteTag(that,i){
          that.attr_vals.splice(i, 1)
          this.saveAttrs(that)
      },
      // 将对 attr_vals 的操作，保存到数据库
      async saveAttrs(that){
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${that.attr_id}`,{
          attr_name: that.attr_name,
          attr_sel: that.attr_sel,
          attr_vals: that.attr_vals.join(' ')
        });
        if (res.meta.status !== 200) return this.$message.error("编辑属性参数失败!");          
        this.$message.success("编辑属性参数成功!");  
      }
   },
   computed:{
      isBtnClick(){
        if(this.selectKeys.length !== 3){
          return true
        }else{
          return false
        }
      },
      // 当前选中的三级 ID
      cateId(){
        if(this.selectKeys.length === 3){
          return this.selectKeys[2]
        }else{
          return null
        }
      },
      // 动态计算标题的文本
      titleText(){
        if(this.activeName === 'many'){
          return '动态参数'
        }else{
          return '静态属性'
        }
      }
   }
 }
</script>

<style lang="scss" scoped>
.params{
  .el-card{
    margin: 30px 0;
    .el-row{
      margin: 30px 0;
    }
    .el-tag{
      margin-right: 6px;
      &:nth-of-type(1){
        margin-left: 50px;
      }
    }
    .input-new-tag{
      width: 120px;
    }

  }
}
</style>